{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文件1: D:/张延兴\\3.txt\n",
      "文件2: D:/张延兴\\5.txt\n",
      "------\n",
      "文件1: D:/张延兴\\3.txt\n",
      "文件2: D:/张延兴\\6.txt\n",
      "------\n",
      "文件1: D:/张延兴\\5.txt\n",
      "文件2: D:/张延兴\\3.txt\n",
      "------\n",
      "文件1: D:/张延兴\\5.txt\n",
      "文件2: D:/张延兴\\6.txt\n",
      "------\n",
      "文件1: D:/张延兴\\6.txt\n",
      "文件2: D:/张延兴\\3.txt\n",
      "------\n",
      "文件1: D:/张延兴\\6.txt\n",
      "文件2: D:/张延兴\\5.txt\n",
      "------\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import filecmp\n",
    "\n",
    "def find_duplicate_files(root_dir):\n",
    "    # 用于存储文件路径和内容的字典\n",
    "    file_contents = {}\n",
    "\n",
    "    # 遍历文件夹及其子文件夹\n",
    "    for dirpath, dirnames, filenames in os.walk(root_dir):\n",
    "        for filename in filenames:\n",
    "            file_path = os.path.join(dirpath, filename)\n",
    "            # 读取文件内容并存储到字典中\n",
    "            with open(file_path, 'rb') as f:\n",
    "                file_content = f.read()\n",
    "                file_contents[file_path] = file_content\n",
    "\n",
    "    # 比较文件内容并找出重复的文件\n",
    "    duplicate_files = []\n",
    "    for file_path1, content1 in file_contents.items():\n",
    "        for file_path2, content2 in file_contents.items():\n",
    "            if file_path1 != file_path2 and content1 == content2:\n",
    "                duplicate_files.append((file_path1, file_path2))\n",
    "\n",
    "    return duplicate_files\n",
    "\n",
    "# 指定文件夹路径\n",
    "root_dir = 'D:/张延兴'\n",
    "\n",
    "# 查找重复文件\n",
    "duplicates = find_duplicate_files(root_dir)\n",
    "\n",
    "# 输出重复文件名和路径\n",
    "for file_path1, file_path2 in duplicates:\n",
    "    print(f\"文件1: {file_path1}\")\n",
    "    print(f\"文件2: {file_path2}\")\n",
    "    print(\"------\")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
